package com.wbl.train.common.handler;

import cn.hutool.core.bean.BeanUtil;
import com.wbl.train.common.result.R;
import com.wbl.train.common.result.ResultCode;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class Global404ExceptionHandler extends BasicErrorController {

    public Global404ExceptionHandler(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        //设置响应错误状态码404
        final HttpStatus status = getStatus(request);
        Map<String, Object> originalMsgMap = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        // 封装数据为统一响应格式
        final R<Map<String, Object>> errorR = R.error(ResultCode.NO_HANDLER_FOUND,originalMsgMap);
        // 将R对象转换为map集合
        final Map<String, Object> errorMap = BeanUtil.beanToMap(errorR);

        return new ResponseEntity<>(errorMap, status);
    }
}
